package com.cool.collect.demo;


import java.util.Arrays;
import java.util.List;
import java.util.Stack;

public class StackExpression {

    //只初始化一次
    private final List<Character> leftBrackets =
            Arrays.asList('<','(','{','[');
    private final List<Character> rightBrackets =
            Arrays.asList('>',')','}',']');

    public  boolean Expression(String input){

        Stack<Character> stack = new Stack<>();
        for(char ch:input.toCharArray()){
            if(isLeftBracket(ch)){
                //如果是左括号，则压入栈
                stack.push(ch);
            }
            else if(isRightBracket(ch)){
                //检查栈是否为空
                if(stack.empty())
                    return false;

                //弹出最顶端的左括号
                var top = stack.pop();
                if(bracketMatch(top,ch))
                    return  false;
            }
        }
        return stack.empty();
    }
    private boolean isLeftBracket (char ch){
        return leftBrackets.contains(ch);
    }

    private boolean isRightBracket (char ch){
        return rightBrackets.contains(ch);
    }

    private  boolean bracketMatch(char left,char right){
        //([{
        //)]}
        return   leftBrackets.indexOf(left) == rightBrackets.indexOf(right);
    }
}

